<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\CouponCodeUnavailableException;
use App\Http\Requests\Api\OrderRequest;
use App\Models\CouponCode;
use App\Models\Order;
use App\Models\UserAddress;
use App\Services\OrderService;
use App\Transformers\ProductTransformer;
use Illuminate\Http\Request;

class OrdersController extends Controller
{
    //用户提交订单
    public function store(OrderRequest $request, OrderService $orderService)
    {
        $user    = $request->user();
        $address = UserAddress::find($request->input('address_id'));
        $coupon  = null;

        //如果用户提交了优惠码
        if($code = $request->input('coupon_code')){
            $coupon = CouponCode::where('code', $code)->first();
            if (!$coupon) {
                throw new CouponCodeUnavailableException('优惠券不存在');
            }
        }
        return $orderService->store($user, $address, $request->input('remark'), $request->input('items'),$coupon);
    }


    // 订单展示页面
    public function index(Request $request)
    {
        $orders = Order::query()
            //使用with预加载 避免N+1 问题
            ->with(['items.product','items.productSku'])
            ->where('user_id',$request->user()->id)
            ->orderBy('created_at','desc')
            ->paginate();

        return $this->response->array(['orders' =>$orders]);
    }

    public function show(Order $order, Request $request)
    {
        $this->authorize('own', $order);
        return $this->response->array(['order' => $order->load(['items.productSku', 'items.product'])]);

    }


}
